package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.merchant.domain.MerchantPrinter;
import com.ruoyi.merchant.domain.dto.PrinterSubmitDTO;
import com.ruoyi.merchant.mapper.MerchantPrinterMapper;
import com.ruoyi.merchant.service.IMerchantPrinterService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商家打印机Service业务层处理
 */
@Service
public class MerchantPrinterServiceImpl implements IMerchantPrinterService {

    @Autowired
    private MerchantPrinterMapper printerMapper;

    @Override
    public MerchantPrinter selectPrinterByPrinterId(Long printerId) {
        MerchantPrinter printer = printerMapper.selectPrinterByPrinterId(printerId);
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        if (printer == null) {
            throw new ServiceException("打印机不存在");
        }
        if (!merchantId.equals(printer.getMerchantId())) {
            throw new ServiceException("无权访问该打印机");
        }
        
        return printer;
    }

    @Override
    public List<MerchantPrinter> selectPrinterList() {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        return printerMapper.selectPrinterList(merchantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPrinter(PrinterSubmitDTO printerDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 检查序列号是否已存在
        MerchantPrinter existPrinter = printerMapper.selectByPrinterSn(printerDTO.getPrinterSn());
        if (existPrinter != null) {
            throw new ServiceException("打印机序列号已被使用");
        }

        MerchantPrinter printer = new MerchantPrinter();
        printer.setMerchantId(merchantId);
        printer.setPrinterName(printerDTO.getPrinterName());
        printer.setPrinterBrand(printerDTO.getPrinterBrand());
        printer.setPrinterModel(printerDTO.getPrinterModel());
        printer.setPrinterSn(printerDTO.getPrinterSn());
        printer.setPrinterKey(printerDTO.getPrinterKey());
        printer.setConnectionType(printerDTO.getConnectionType());
        printer.setIpAddress(printerDTO.getIpAddress());
        printer.setPort(printerDTO.getPort());
        printer.setPrintWidth(printerDTO.getPrintWidth() != null ? printerDTO.getPrintWidth() : 58);
        printer.setAutoPrintOrder(printerDTO.getAutoPrintOrder() != null ? printerDTO.getAutoPrintOrder() : 1);
        printer.setPrintCopies(printerDTO.getPrintCopies() != null ? printerDTO.getPrintCopies() : 1);
        printer.setIsDefault(0);
        printer.setIsOnline(0);
        printer.setStatus(1);

        // 如果是第一台打印机，设为默认
        List<MerchantPrinter> existList = printerMapper.selectPrinterList(merchantId);
        if (existList.isEmpty()) {
            printer.setIsDefault(1);
        }

        return printerMapper.insertPrinter(printer);
    }

    @Override
    public int updatePrinterStatus(Long printerId, Integer status) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        MerchantPrinter printer = printerMapper.selectPrinterByPrinterId(printerId);
        if (printer == null || !merchantId.equals(printer.getMerchantId())) {
            throw new ServiceException("无权操作该打印机");
        }

        MerchantPrinter updatePrinter = new MerchantPrinter();
        updatePrinter.setPrinterId(printerId);
        updatePrinter.setMerchantId(merchantId);
        updatePrinter.setStatus(status);

        return printerMapper.updatePrinter(updatePrinter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePrinter(PrinterSubmitDTO printerDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Long printerId = printerDTO.getPrinterId();

        if (printerId == null) {
            throw new ServiceException("打印机ID不能为空");
        }

        // 验证打印机存在且属于当前商家
        MerchantPrinter existPrinter = printerMapper.selectPrinterByPrinterId(printerId);
        if (existPrinter == null) {
            throw new ServiceException("打印机不存在");
        }
        if (!merchantId.equals(existPrinter.getMerchantId())) {
            throw new ServiceException("无权修改该打印机");
        }

        // 如果修改了序列号，检查新序列号是否已被使用
        if (!existPrinter.getPrinterSn().equals(printerDTO.getPrinterSn())) {
            MerchantPrinter snPrinter = printerMapper.selectByPrinterSn(printerDTO.getPrinterSn());
            if (snPrinter != null) {
                throw new ServiceException("打印机序列号已被使用");
            }
        }

        MerchantPrinter printer = new MerchantPrinter();
        printer.setPrinterId(printerId);
        printer.setMerchantId(merchantId);
        printer.setPrinterName(printerDTO.getPrinterName());
        printer.setPrinterBrand(printerDTO.getPrinterBrand());
        printer.setPrinterModel(printerDTO.getPrinterModel());
        printer.setPrinterSn(printerDTO.getPrinterSn());
        printer.setPrinterKey(printerDTO.getPrinterKey());
        printer.setConnectionType(printerDTO.getConnectionType());
        printer.setIpAddress(printerDTO.getIpAddress());
        printer.setPort(printerDTO.getPort());
        printer.setPrintWidth(printerDTO.getPrintWidth());
        printer.setAutoPrintOrder(printerDTO.getAutoPrintOrder());
        printer.setPrintCopies(printerDTO.getPrintCopies());

        return printerMapper.updatePrinter(printer);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePrinterByPrinterId(Long printerId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        MerchantPrinter printer = printerMapper.selectPrinterByPrinterId(printerId);
        if (printer == null || !merchantId.equals(printer.getMerchantId())) {
            throw new ServiceException("无权删除该打印机");
        }

        return printerMapper.deletePrinterByPrinterId(printerId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePrinterByPrinterIds(Long[] printerIds) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        for (Long printerId : printerIds) {
            MerchantPrinter printer = printerMapper.selectPrinterByPrinterId(printerId);
            if (printer == null || !merchantId.equals(printer.getMerchantId())) {
                throw new ServiceException("包含无权删除的打印机");
            }
        }

        int count = 0;
        for (Long printerId : printerIds) {
            count += printerMapper.deletePrinterByPrinterId(printerId);
        }
        return count;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setDefaultPrinter(Long printerId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        MerchantPrinter printer = printerMapper.selectPrinterByPrinterId(printerId);
        if (printer == null || !merchantId.equals(printer.getMerchantId())) {
            throw new ServiceException("无权操作该打印机");
        }

        // 重置其他打印机的默认状态
        printerMapper.resetDefaultPrinter(merchantId);

        // 设置当前打印机为默认
        return printerMapper.setDefaultPrinter(printerId, merchantId);
    }

    @Override
    public int testPrint(Long printerId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        MerchantPrinter printer = printerMapper.selectPrinterByPrinterId(printerId);
        if (printer == null || !merchantId.equals(printer.getMerchantId())) {
            throw new ServiceException("无权操作该打印机");
        }

        if (printer.getStatus() != 1) {
            throw new ServiceException("打印机未启用");
        }

        // 构建测试打印内容
        String content = buildTestContent(printer);

        // TODO: 调用打印机SDK进行测试打印
        return 1;
    }

    private String buildTestContent(MerchantPrinter printer) {
        String line = printer.getPrintWidth() == 58 ? "--------------------------------" : "------------------------------------------------";
        
        StringBuilder sb = new StringBuilder();
        sb.append("<CB>打印机测试</CB>\n");
        sb.append(line).append("\n");
        sb.append("打印机名称：").append(printer.getPrinterName()).append("\n");
        sb.append("打印机型号：").append(printer.getPrinterModel()).append("\n");
        sb.append("序列号：").append(printer.getPrinterSn()).append("\n");
        sb.append(line).append("\n");
        sb.append("测试时间：").append(new java.util.Date()).append("\n");
        sb.append("\n\n\n");
        
        return sb.toString();
    }
}
